﻿// RegisterUserModel class
// This class is the definition of the model of Register
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using AnalisisDeRiesgos.Dal;
using System.Web.Mvc;
using System.Collections.Generic;

namespace AnalisisDeRiesgos.Models.User
{
    [PasswordMatch("Password", "RePassword")]
    public class RegisterUserModel
    {
        [DisplayName("CI *")]
        [Required(ErrorMessage="El CI es requerido")]
        [StringLength(10, ErrorMessage="El CI no puede sobrepasar los 10 numeros")]
        [RegularExpression(@"^\d+$", ErrorMessage = "El CI solo puede ser valores numericos")]
        public string CI { get; set; }

        [DisplayName("Nombre(s) *")]
        [Required(ErrorMessage= "El nombre es requerido")]
        [StringLength(50, ErrorMessage="El nombre debe ser máximo de 50 caracteres")]
        [RegularExpression(@"^[a-zA-Z ñÑáéíóúÁÉÍÓÚ]+$", ErrorMessage = "El nombre debe ser solo letras mayusculas o minusculas")]
        public String FirstName { set; get; } // The First Name of the user

        [DisplayName("Apellido Paterno *")]
        [Required(ErrorMessage = "El apellido paterno es requerido")]
        [StringLength(50, ErrorMessage="El apellido paterno debe ser máximo de 50 caracteres")]
        [RegularExpression(@"^[a-zA-Z ñÑáéíóúÁÉÍÓÚ]+$", ErrorMessage = "El apellido paterno debe ser solo letras mayusculas o minusculas")]
        public String LastName { set; get; } // The Last name of the user

        [DisplayName("Apellido Materno *")]
        [Required(ErrorMessage = "El apellido materno es requerido")]
        [StringLength(50, ErrorMessage="El apellido materno debe ser máximo de 50 caracteres")]
        [RegularExpression(@"^[a-zA-Z ñÑáéíóúÁÉÍÓÚ ]+$", ErrorMessage = "El apellido materno debe ser solo letras mayusculas o minusculas")]
        public String SecondLastName { set; get; } // The second last name of the user

        [DisplayName("Privilegios *")]
        [Required(ErrorMessage = "El privilegio es requerido")]
        public int Privilege { set; get; }

        [DisplayName("Contraseña *")]
        [DataType(DataType.Password)]
        [Required(ErrorMessage = "La contraseña es requerida")]
        [StringLength(50, ErrorMessage="La contraseña debe ser máximo de 50 caracteres y minimo 6 caracteres", MinimumLength=6)]
        public String Password { set; get; } // The password that the user will input

        [DisplayName("Re escriba la contraseña")]
        [DataType(DataType.Password)]
        public String RePassword { set; get; } // The passowrd that the user must re input

        public IEnumerable<SelectListItem> PrivilegeList
        {
            get
            {
                return privilegeList;
            }
        }

        private List<SelectListItem> privilegeList;

        private riskanalysisEntities entities = new riskanalysisEntities(); // A reference to Entities

        public RegisterUserModel()
        {
            privilegeList = new List<SelectListItem>();

            privilegeList.Add(new SelectListItem
            {
                Text = "Administrador",
                Value = Convert.ToInt32(Privileges.Administrator).ToString()
            });

            privilegeList.Add(new SelectListItem
            {
                Text = "Gerente General de Seguridad",
                Value = Convert.ToInt32(Privileges.GeneralSecurity).ToString(),
            });

            privilegeList.Add(new SelectListItem
            {
                Text = "Encargado de Seguridad de Area",
                Value = Convert.ToInt32(Privileges.AreaSecurity).ToString(),
            });

            privilegeList.Add(new SelectListItem
            {
                Text = "Empleado",
                Value = Convert.ToInt32(Privileges.Employe).ToString(),
            });
        }

        // This method saves a new user with the actual information
        public void Save()
        {
            int theCI = Convert.ToInt32(this.CI);
            if ((from u in entities.users
                 where u.CI == theCI
                 select u).Count() >= 1)
                throw new RegisterUserException("El CI con el que intenta registrar ya existe!");
            entities.AddTousers(new user
            {
                CI = Convert.ToInt32(this.CI),
                firstName = FirstName,
                lastName = LastName,
                secondLastName = SecondLastName,
                username = GetUserName(),
                privilege = Privilege,
                password = Utils.CalculateSHA1(Password),
                enabled = true
            });
            entities.SaveChanges();
        } // end method Save

        // This method will return the possible new UserName
        private string GetUserName()
        {
            var usernames = from user in entities.users
                                  select user.username;
            string username = FirstName.Trim()[0].ToString() + LastName.Trim()[0].ToString() + SecondLastName.Trim()[0].ToString();

            username = username.ToLower();

            if (!usernames.Contains(username))
                return username;

            int val = 1;
            
            while (usernames.Contains(username + val))
            {
                ++val;
            }

            return username + val;
        } // end method GetUserName
    } // end class RegisterUserModel
}